package com.lzh.hosp.listener;

import com.lzh.hosp.model.OrderInfo;
import com.lzh.hosp.model.Schedule;
import com.lzh.hosp.service.OrderInfoService;
import com.lzh.hosp.service.ScheduleService;
import com.lzh.hosp.utils.RedisCache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.listener.KeyExpirationEventMessageListener;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

@Component
public class RedisKeyExpirationListener extends KeyExpirationEventMessageListener {
    @Autowired
    private RedisCache redisCache;

    @Autowired
    private OrderInfoService orderInfoService;

    @Autowired
    private ScheduleService scheduleService;
 
    public RedisKeyExpirationListener(RedisMessageListenerContainer listenerContainer) {
        super(listenerContainer);
    }
 
    @Override
    public void onMessage(Message message, byte[] pattern) {
        // 过期key，可以设置成订单号
        String expiredKey = message.toString();
        // 取消订单业务逻辑
        // 找出是否存在备份键
        Object cacheObject = redisCache.getCacheObject(expiredKey + "orderInfo");
        if (StringUtils.isEmpty(cacheObject)){//说明过期的只是token
            return;
        }
        redisCache.deleteObject(expiredKey + "orderInfo");
        //将数据库中对应的订单号状态修改
        OrderInfo orderInfo = orderInfoService.getById(expiredKey);
        orderInfo.setOrderStatus(1);//1表示已超时
        orderInfoService.updateById(orderInfo);

        //排班余量恢复
        Schedule schedule = scheduleService.getById(orderInfo.getScheduleId());
        schedule.setAvailableNumber(schedule.getAvailableNumber()+1);
        scheduleService.updateById(schedule);
    }
}